/**
 * 
 */
package com.fandy.struts.action;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

import com.fandy.struts.DAL.*;
import com.fandy.struts.util.*;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.*;

import com.fandy.struts.form.FormLogin;



/**
 * @author Administrator
 *
 */
public class ActionLogin extends DispatchAction {
	
	

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		ActionForward af = new ActionForward();
		ActionErrors ae = new ActionErrors();
		FormLogin formLogin = (FormLogin)form;
		
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
		}
		
		if(Valid(formLogin))
		{
			
			af = mapping.findForward(MappingForward.Success);
		}
		else
		{
			ae.add(ActionErrors.GLOBAL_MESSAGE,new ActionMessage("Error.Login.UserName"));
			saveErrors(request, ae);
			af = mapping.findForward(MappingForward.Failure);			
		}
		
		request.getSession().setAttribute("UserInfo", formLogin);
	 		
		return af; 
	
	}
	
	private boolean Valid(FormLogin fl) throws SQLException
	{
		boolean b = false;
		
		DALStaff Stf = new DALStaff();
		
		int num=0;
		ResultSet rs =Stf.existStaff4Login(fl.getStaff());
		
		if(rs.first())
			{
				try
				{
					num= rs.getInt(1);
				}
				catch(Exception e)
				{
					e.printStackTrace();			
				}
			}
		if(num==1)
		{
		 b=true;		
		}
		
		return b;
	}
	
	
}
